//
// Created by LIN on 25-9-9.
//
#include "single_linked_list.h"

void print_list(const ListNode *list)
{
    const ListNode *current = list;
    while (current)
    {
        printf("%d->", current->val);
        current = current->next;
    }
    printf("NULL\n");
}

void push_back(ListNode **head, const TypeData x)
{
    ListNode *newNode = malloc(sizeof(ListNode));
    if (newNode == NULL)
    {
        printf("分配空间失败\n");
        exit(-1);
    }
    newNode->next = NULL;
    newNode->val = x;

    if (*head == NULL)
    {
        *head = newNode;
        return;
    }

    ListNode *current = *head;

    while (current->next)
        current = current->next;

    current->next = newNode;
}

void push_front(ListNode **head, const TypeData x)
{
    ListNode *newNode = malloc(sizeof(ListNode));
    if (newNode == NULL)
    {
        printf("空间分配失败\n");
        exit(-1);
    }

    newNode->next = *head;
    newNode->val = x;
    *head = newNode;
}

void pop_back(ListNode **head)
{
    assert(*head != NULL);
    if ((*head)->next == NULL)
    {
        free(*head);
        *head = NULL;
        return;
    }
    ListNode *current = *head;
    ListNode *prev = NULL;
    while (current->next)
    {
        prev = current;
        current = current->next;
    }
    free(current);
    current = NULL;
    if (prev != NULL)
        prev->next = NULL;
}

void pop_front(ListNode **head)
{
    assert(*head != NULL);
    ListNode *prev = (*head)->next;
    free(*head);
    *head = prev;
}

bool find(const ListNode *head, const TypeData x)
{
    const ListNode *current = head;
    while (current)
    {
        if (current->val == x)
            return true;
        current = current->next;
    }
    return false;
}

void erase(ListNode **head, const TypeData x)
{
    ListNode *current = *head;
    ListNode *prev = NULL;
    while (current)
    {
        if (current->val == x)
        {
            ListNode *nextNext = current->next;
            free(current);
            if (prev != NULL)
                prev->next = nextNext;
            else
                *head = nextNext;
            return;
        }
        prev = current;
        current = current->next;
    }
}